package me.ingxin.android.router.compiler.processor

import me.ingxin.android.router.compiler.util.Logger
import me.ingxin.android.router.compiler.util.ProcessorUtil
import javax.annotation.processing.AbstractProcessor
import javax.annotation.processing.ProcessingEnvironment
import javax.annotation.processing.RoundEnvironment
import javax.lang.model.SourceVersion
import javax.lang.model.element.TypeElement

/**
 * Created by ingxin on 2022/4/16
 */
class InterceptorAnnotationProcessor : AbstractProcessor() {

    private lateinit var interceptorProcessor: InterceptorProcessor
    private lateinit var appProcessor: InterceptorAppProcessor
    private lateinit var logger: Logger

    @Synchronized
    override fun init(processingEnv: ProcessingEnvironment) {
        super.init(processingEnv)
        logger = Logger(processingEnv.messager)
        val processorUtil = ProcessorUtil(processingEnv)
        interceptorProcessor = InterceptorProcessor(processorUtil, logger)
        appProcessor = InterceptorAppProcessor(processorUtil, logger)
    }

    override fun getSupportedAnnotationTypes(): MutableSet<String> {
        return HashSet<String>().apply {
            addAll(appProcessor.getSupportedAnnotationTypes())
            addAll(interceptorProcessor.getSupportedAnnotationTypes())
        }
    }

    override fun getSupportedSourceVersion(): SourceVersion {
        return SourceVersion.latestSupported()
    }

    override fun process(set: MutableSet<out TypeElement>, env: RoundEnvironment): Boolean {
        if (set.isEmpty()) {
            return false
        }
        val t = System.currentTimeMillis()
        val appOwner = appProcessor.checkApp(env)
        if (appOwner != null) {
            appProcessor.process(appOwner, interceptorProcessor.getInterceptor(env))
            logger.info("InterceptorAnnotationProcessor cost ${System.currentTimeMillis() - t}ms")
            //当前注解可以继续被其他处理器处理
            return false
        } else {
            interceptorProcessor.process(env)
            logger.info("InterceptorAnnotationProcessor cost ${System.currentTimeMillis() - t}ms")
        }
        return true
    }


}